//
//  GIMapViewController.m
//  地图导航dome
//
//  Created by xu yao on 2021/3/12.
//

#import "GIMapViewController.h"
#import "UIView+Extension.h"
#import "NaviTopTurnImageView.h"
#import <AMapNaviKit/AMapNaviKit.h>
#import "GAppConfig.h"
#import "NaviCountDownView.h"
#import "CSButton.h"
#import "NaviSpeedView.h"

@interface GIMapViewController () <AMapNaviDriveViewDelegate, AMapNaviDriveManagerDelegate, AMapNaviDriveDataRepresentable>

@property (nonatomic, strong) AMapNaviDriveView *driveView;
@property (nonatomic, strong) AMapNaviTrafficBarView *trafficBarView;   //路况指示图
@property (nonatomic, weak) UIButton *rightBrowserBtn;  //全览按钮
@property (nonatomic, weak) UIImageView *crossImageView;    //放大的预览图
@property (nonatomic, weak) NaviTopTurnImageView *turnImageView;    //顶部路线指示图
@property (nonatomic, strong) NaviSpeedView *speedView;     //速度指示器
@property (nonatomic, weak) NaviCountDownView *countView;       //倒计时

@end

@implementation GIMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initDriveView];
    
//    [self initCustomUI];
    [self initDriveManager];
    [self initPOIInfo];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)initCustomUI {
//    NaviBottomView *bottomView = [NaviBottomView naviBottomView];
//    bottomView.height += [DeviceTool isIphoneX] ? 20 : 0;
//    bottomView.bottom = Screen_Height;
//    bottomView.nameLabel.text = self.contacts;
//    bottomView.addressLabel.text = self.addressDetail;
//    bottomView.orderId = self.orderId;
//    bottomView.waybillNo = self.waybillNo;
//    bottomView.waybillStatus = self.waybillStatus;
//    bottomView.phoneString = self.phoneString;
//    [self.view addSubview:bottomView];
//    [bottomView.closeButton addTarget:self action:@selector(onTapClose) forControlEvents:UIControlEventTouchUpInside];
//    __weak typeof(self) weakSelf = self;
//    [bottomView setCheckCodeSuccess:^(BOOL isSuccess) {
//        //发送成功的消息
//        if (weakSelf.checkCodeSuccess) {
//            weakSelf.checkCodeSuccess(isSuccess);
//        }
//        [weakSelf.navigationController popViewControllerAnimated:YES];
//    }];
    
    NaviCountDownView *countView = [NaviCountDownView countDownView:CGPointMake(12, Screen_Height - 12 - 50)];
    [self.view addSubview:countView];
    _countView = countView;
    
    CSButton *allButton = [CSButton buttonWithType:UIButtonTypeCustom];
    allButton.titleLabel.font = [UIFont systemFontOfSize:10];
    [allButton setImage:[UIImage imageNamed:@"default_navi_browse_ver_normal"] forState:UIControlStateNormal];
    [allButton setImage:[UIImage imageNamed:@"default_navi_browse_ver_selected"] forState:UIControlStateSelected];
//    allButton.backgroundColor = [UIColor whiteColor];
    allButton.size = CGSizeMake(50, 50);
    allButton.right = Screen_Width - 12;
    allButton.top = countView.top;
    [self.view addSubview:allButton];
    [allButton addTarget:self action:@selector(onTapAllButton:) forControlEvents:UIControlEventTouchUpInside];
    _rightBrowserBtn = allButton;
    
    NaviTopTurnImageView *turnImageView = [[NaviTopTurnImageView alloc] initWithFrame:CGRectMake(12, StatusBarHeihgt + 12, Screen_Width - 24, 105)];
    [self.view addSubview:turnImageView];
    _turnImageView = turnImageView;
        
    self.speedView = [NaviSpeedView speedView:CGPointMake(12, self.turnImageView.bottom + 12)];
    [self.view addSubview:self.speedView];
    
    self.trafficBarView = [[AMapNaviTrafficBarView alloc] init];
    self.trafficBarView.size = CGSizeMake(14, allButton.top - 12 - 12 - self.turnImageView.bottom);
    self.trafficBarView.right = Screen_Width - 12;
    self.trafficBarView.bottom = allButton.top - 12;
    self.trafficBarView.layer.masksToBounds = YES;
    self.trafficBarView.layer.cornerRadius = 7;
    self.trafficBarView.layer.borderWidth = 4;
    self.trafficBarView.layer.borderColor = [UIColor whiteColor].CGColor;
    [self.view addSubview:self.trafficBarView];
    
    UIImageView *crossImageView = [[UIImageView alloc] initWithFrame:CGRectMake(12, turnImageView.bottom, turnImageView.width, 204)];
    [self.view addSubview:crossImageView];
    _crossImageView = crossImageView;
}

- (void)initDriveView {
    if (self.driveView == nil) {
        self.driveView = [[AMapNaviDriveView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
        
        self.driveView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        [self.driveView setDelegate:self];
        self.driveView.trackingMode = AMapNaviViewTrackingModeCarNorth;
        self.driveView.showMode = AMapNaviDriveViewShowModeCarPositionLocked;
//        self.driveView.showUIElements = NO;
        self.driveView.showGreyAfterPass = YES;
        self.driveView.autoZoomMapLevel = YES;
        self.driveView.showTrafficBar = NO;
        self.driveView.showMoreButton = NO;
        self.driveView.autoSwitchShowModeToCarPositionLocked = YES;
        [self.driveView setCarImage:[UIImage imageNamed:@"item／当前位置"]];
        [self.view addSubview:self.driveView];
    }
}

- (void)initDriveManager {
    [[AMapNaviDriveManager sharedInstance] setDelegate:self];
    [[AMapNaviDriveManager sharedInstance] setDetectedMode:AMapNaviDetectedModeCameraAndSpecialRoad];
    //将self 、driveView、trafficBarView 添加为导航数据的Representative，使其可以接收到导航诱导数据
    [[AMapNaviDriveManager sharedInstance] addDataRepresentative:self.driveView];
    [[AMapNaviDriveManager sharedInstance] addDataRepresentative:self.trafficBarView];
    [[AMapNaviDriveManager sharedInstance] addDataRepresentative:self];
}

- (void)initPOIInfo {
    AMapNaviPOIInfo *startInfo = [[AMapNaviPOIInfo alloc] init];
    startInfo.locPoint = self.startPoint;
//    startInfo.startAngle = 270;
       
    AMapNaviPOIInfo *endInfo = [[AMapNaviPOIInfo alloc] init];
    endInfo.locPoint = self.endPoint;
//    endInfo.mid = @"B000A8UIN8";
       
    [[AMapNaviDriveManager sharedInstance] calculateDriveRouteWithStartPOIInfo:startInfo endPOIInfo:endInfo wayPOIInfos:nil drivingStrategy:AMapNaviDrivingStrategySingleDefault];
}

- (void)onTapClose {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确定退出导航" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popViewControllerAnimated: YES];
    }];
    UIAlertAction *backAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:backAction];
    [alertController addAction:yesAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)onTapAllButton:(UIButton *)button {
    if (self.driveView.showMode == AMapNaviDriveViewShowModeOverview) {
        self.driveView.showMode = AMapNaviDriveViewShowModeCarPositionLocked;
    } else {
        self.driveView.showMode = AMapNaviDriveViewShowModeOverview;
    }
}

#pragma mark 路径规划成功后
- (void)driveManager:(AMapNaviDriveManager *)driveManager onCalculateRouteSuccessWithType:(AMapNaviRoutePlanType)type {
    //算路成功后开始GPS导航
    [[AMapNaviDriveManager sharedInstance] startGPSNavi];
    if (self.imapDelegate && [self.imapDelegate respondsToSelector:@selector(gcongoIMapWithOnCalculateRouteSuccess)]) {
        [self.imapDelegate gcongoIMapWithOnCalculateRouteSuccess];
    }
}

#pragma mark 实时导航到达目的地
- (void)driveManagerOnArrivedDestination:(AMapNaviDriveManager *)driveManager {
    if (self.imapDelegate && [self.imapDelegate respondsToSelector:@selector(gcongoIMapOnArrivedDestination)]) {
        [self.imapDelegate gcongoIMapOnArrivedDestination];
    }
}

//显示路口放大图
- (void)driveManager:(AMapNaviDriveManager *)driveManager showCrossImage:(UIImage *)crossImage {
    [self handleWhenCrossImageShowAndHide:crossImage];
}

//隐藏路口放大图
- (void)driveManagerHideCrossImage:(AMapNaviDriveManager *)driveManager {
    [self handleWhenCrossImageShowAndHide:nil];
}

- (void)driveView:(AMapNaviDriveView *)driveView didChangeShowMode:(AMapNaviDriveViewShowMode)showMode {
    if (showMode == AMapNaviDriveViewShowModeOverview) {
        self.rightBrowserBtn.selected = YES;
    } else {
        self.rightBrowserBtn.selected = NO;
    }
    
    if (showMode != AMapNaviDriveViewShowModeCarPositionLocked) {  //非锁车，隐藏路口放大图
        [self handleWhenCrossImageShowAndHide:nil];
    }
}

#pragma mark - AMapNaviDriveDataRepresentable

- (void)driveViewCloseButtonClicked:(AMapNaviDriveView *)driveView {
    if (self.imapDelegate && [self.imapDelegate respondsToSelector:@selector(gcongoIMapCloseButtonClicked)]) {
        [self.imapDelegate gcongoIMapCloseButtonClicked];
    } else {
        [self onTapClose];
    }
}
//诱导信息
- (void)driveManager:(AMapNaviDriveManager *)driveManager updateNaviInfo:(AMapNaviInfo *)naviInfo {
    if (naviInfo) {
        NSString *remainString = [NSString stringWithFormat:@"%@",[self normalizedRemainDistance:naviInfo.segmentRemainDistance]];
        NSMutableAttributedString *attStr = [[NSAttributedString alloc] initWithString:remainString].mutableCopy;
        [attStr addAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:20]} range:NSMakeRange(remainString.length - 1, 1)];
        self.turnImageView.topRemainLabel.attributedText = attStr;
        self.turnImageView.topRoadLabel.text = naviInfo.nextRoadName;
        
        NSString *remainTime = [self normalizedRemainTime:naviInfo.routeRemainTime];
        NSString *remainDis = [self normalizedRemainDistance:naviInfo.routeRemainDistance];
        self.countView.countDownLabel.text = [NSString stringWithFormat:@"%@ %@",remainDis,remainTime];
        NSString *arrivalTime = [self normalizedArrivalTime:naviInfo.routeRemainTime];
        self.countView.timeLabel.text = [NSString stringWithFormat:@"%@到达", arrivalTime];
        [self.turnImageView layoutSubviews];
        [self.countView layoutSubviews];
        
        self.countView.numberLabel.text = [NSString stringWithFormat:@"%ld", naviInfo.routeRemainTrafficLightCount];
    }
}
//转向图标
- (void)driveManager:(AMapNaviDriveManager *)driveManager updateTurnIconImage:(UIImage *)turnIconImage turnIconType:(AMapNaviIconType)turnIconType {
    if (turnIconImage) {
        self.turnImageView.topTurnImageView.image = turnIconImage;
        [self.turnImageView layoutSubviews];
    }
}

- (void)driveManager:(AMapNaviDriveManager *)driveManager updateNaviLocation:(AMapNaviLocation *)naviLocation {
    if (naviLocation) {
        self.speedView.speedLabel.text = [NSString stringWithFormat:@"%ld", (long)naviLocation.speed];
        [self.speedView layoutSubviews];
    }
}

//处理路口放大图
- (void)handleWhenCrossImageShowAndHide:(UIImage *)crossImage {
    if (crossImage && self.driveView.showMode == AMapNaviDriveViewShowModeCarPositionLocked) {
        self.rightBrowserBtn.hidden = YES;
        self.trafficBarView.hidden = YES;
        self.speedView.hidden = YES;
        self.countView.hidden = YES;
    } else {
        self.rightBrowserBtn.hidden = NO;
        self.trafficBarView.hidden = NO;
        self.speedView.hidden = NO;
        self.countView.hidden = NO;
    }
    [self updateMapViewScreenAnchor];
}

//更新地图锚点
- (void)updateMapViewScreenAnchor {
    [self.view layoutIfNeeded];
    
    CGFloat x = 0.5;
    CGFloat y = 0.75;
    
    if(self.driveView.isLandscape) {  //横屏模式
        CGFloat xStart = self.trafficBarView.frame.origin.x + self.trafficBarView.frame.size.width;
        CGFloat xEnd = self.driveView.bounds.size.width - 80;
        if (self.crossImageView.image) {
            xStart = self.trafficBarView.frame.origin.x - 10;
            xEnd = self.driveView.bounds.size.width;
            y = 0.7;
        } else {
            y = 0.55;
        }
        CGFloat xAreaMiddleInAll = (xEnd - xStart) / 2 + xStart;
        x = xAreaMiddleInAll / self.driveView.bounds.size.width;
    }
    
    if (x <= 0 || x >= 1 ) {
        x = 0.5;
    }
    
    if (self.driveView.screenAnchor.x != x || self.driveView.screenAnchor.y != y) {
        self.driveView.screenAnchor = CGPointMake(x, y);
    }
}

- (NSString *)normalizedRemainDistance:(NSInteger)remainDistance {
    if (remainDistance < 0) {
        return nil;
    }
    
    if (remainDistance >= 1000) {
        CGFloat kiloMeter = remainDistance / 1000.0;
        return [NSString stringWithFormat:@"%.1f公里", kiloMeter];
    } else {
        return [NSString stringWithFormat:@"%ld米", (long)remainDistance];
    }
}

- (NSString *)normalizedRemainTime:(NSInteger)remainTime {
    if (remainTime < 0) {
        return nil;
    }
    
    if (remainTime < 60) {
        return [NSString stringWithFormat:@"< 1分钟"];
    }
    return [NSString stringWithFormat:@"%ld分钟", (long)remainTime/60];
}

- (NSString *)normalizedArrivalTime:(NSInteger)remainTime {
    if (remainTime < 0) {
        return nil;
    }
    // 获取当前时间
    NSInteger currentTime = [[NSDate date] timeIntervalSince1970];
    NSString *today = [self timestampSwitchTime:currentTime andFormatter:@"YYYY-MM-dd"];
    currentTime += remainTime;
    NSString *timestamp = [self timestampSwitchTime:currentTime andFormatter:@"YYYY-MM-dd hh:mm:ss"];
    
    if (timestamp) {
        if ([[timestamp substringToIndex:10] isEqualToString:today]) {
            return [timestamp substringWithRange:NSMakeRange(11, 5)];
        }
        return [timestamp substringWithRange:NSMakeRange(5, 11)];
    }
    return nil;
}

#pragma mark - 将某个时间戳转化成 时间

- (NSString *)timestampSwitchTime:(NSInteger)timestamp andFormatter:(NSString *)format{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    // （@"YYYY-MM-dd hh:mm:ss"）----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    [formatter setDateFormat:format];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:timestamp];
    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
    return confromTimespStr;
}

- (void)dealloc {
    [[AMapNaviDriveManager sharedInstance] stopNavi];
    [[AMapNaviDriveManager sharedInstance] removeDataRepresentative:self.driveView];
    [[AMapNaviDriveManager sharedInstance] removeDataRepresentative:self.trafficBarView];
    [[AMapNaviDriveManager sharedInstance] removeDataRepresentative:self];
    [[AMapNaviDriveManager sharedInstance] setDelegate:nil];
    BOOL success = [AMapNaviDriveManager destroyInstance];
    NSLog(@"单例是否销毁成功 : %d",success);
}

@end
